#pragma once
#include <iostream>
#include <sys/select.h>
#include "Socket.hpp"
#define NUM sizeof(fd_set) * 8
using namespace SocketModule;
using namespace LogMudule;

const int gdefaultfd = -1;

class Select
{
public:
    Select(uint16_t port)
        : _socket(std::make_unique<TcpSocket>()),
          _isrunning(false),
          _port(port)
    {
    }
    ~Select()
    {
    }
    void Init()
    {
        _socket->BuildTcpSocket(_port);
        for (int i = 0; i < NUM; i++)
        {
            _fd_array[i] = gdefaultfd;
        }
        _fd_array[0] = _socket->Fd();
    }
    void Start()
    {
        fd_set rfds;
        _isrunning = true;
        while (true)
        {
            FD_ZERO(&rfds);
            struct timeval tv = {5, 0};
            int maxfd = gdefaultfd;

            for (int i = 0; i < NUM; i++)
            {
                if (_fd_array[i] == gdefaultfd)
                    continue;
                // 合法的fd
                FD_SET(_fd_array[i], &rfds); // 包含listensockfd
                // 更新出最大值
                if (maxfd < _fd_array[i])
                {
                    maxfd = _fd_array[i];
                }
            }
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, &tv);

            switch (n)
            {
            case 0:
                std::cout << "time out" << std::endl;
                break;
            case -1:
                perror("select");
                break;
            default:
                std::cout << "已有用户准备就绪" << std::endl;
                Dispatcher(rfds);
                break;
            }
        }
        
    }
    void Dispatcher(fd_set &rfds)
    {
        for (int i = 0; i < NUM; i++)
        {
            if (_fd_array[i] == gdefaultfd)
                continue;
            // 判断是否在rfds集合中
            if (_fd_array[i] == _socket->Fd())
            {
                // 继续进行连接；
                if (FD_ISSET(_fd_array[i], &rfds))
                {
                    Accpetor();
                }
            }
            else
            {
                // 进行IO
                if (FD_ISSET(_fd_array[i], &rfds))
                {
                    Recver(i);
                }
            }
        }
    }
    void Recver(int who)
    {
        char buffer[1024];
        int n = recv( _fd_array[who] , buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "cilent: #" << buffer << std::endl;
            std::string message;
            message += "Echo #";
            send( _fd_array[who] , message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFO) << "客户端退出 ：" <<  _fd_array[who] ;
            close( _fd_array[who] );
            _fd_array[who] = gdefaultfd;
        }
        else
        {
            LOG(LogLevel::DEBUG) << "客户端读取出错, sockfd: " << _fd_array[who];
            close(_fd_array[who]);
            _fd_array[who] = gdefaultfd;
        }
    }
    void Accpetor()
    {
        InetAddr client;
        int newfd = _socket->Accept(&client);
        if (newfd < 0)
            return;
        // 加入托管
        else
        {
            int pos = -1;
            for (int i = 0; i < NUM; i++)
            {
                if (_fd_array[i] == gdefaultfd)
                {
                    pos = i;
                    break;
                }
            }
            if (pos == -1)
            {
                std::cout << "服务器已满........" << std::endl;
                close(newfd);
            }
            else
            {
                _fd_array[pos] = newfd;
            }
        }
    }

private:
    std::unique_ptr<Socket> _socket;
    bool _isrunning;
    u_int16_t _port;
    int _fd_array[NUM];
};
